package com.cs.dingdingauto.extent

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.FragmentActivity
import java.lang.reflect.Method
import java.util.*

abstract class ExternalActivity : FragmentActivity() {

    companion object {
        var KEY_REQUEST_CODE = "request_code"
        var KEY_FORCE_START = "force_start"
        private val sRequestCodeSet = HashSet<Int>()
    }

    private var requestCode = -1
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestCode = intent.getIntExtra(KEY_REQUEST_CODE, -1)
        if (sRequestCodeSet.contains(requestCode)) {
            //重复展示，关闭此Activity
            super.finish()
        } else {
            collapseStatusBar(applicationContext)
            ExternalActivityUtil.popupCallback?.onPopupShown()
            if (postCreate(savedInstanceState)) {
                sRequestCodeSet.add(requestCode)
                ExternalActivityUtil.onActivityCreated(requestCode)
                Log.i(ExternalActivityUtil.TAG, "RequestCode: ${requestCode}, 展示：${javaClass.simpleName}")
            }
        }
    }

    override fun onStart() {
        super.onStart()
        Log.i(ExternalActivityUtil.TAG, "RequestCode: ${requestCode}, onStart")
    }

    override fun onResume() {
        super.onResume()
        Log.i(ExternalActivityUtil.TAG, "RequestCode: ${requestCode}, onResume")
    }

    override fun onStop() {
        super.onStop()
        Log.i(ExternalActivityUtil.TAG, "RequestCode: ${requestCode}, onStop")
    }

    override fun onPause() {
        super.onPause()
        Log.i(ExternalActivityUtil.TAG, "RequestCode: ${requestCode}, onPause")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(ExternalActivityUtil.TAG, "RequestCode: ${requestCode}, onDestroy")
    }
    abstract fun postCreate(savedInstanceState: Bundle?): Boolean

    fun collapseStatusBar(context: Context) {
        val service = context.getSystemService("statusbar") ?: return
        try {
            val clazz = Class.forName("android.app.StatusBarManager")
            val sdkVersion = Build.VERSION.SDK_INT
            var collapse: Method? = null
            collapse = if (sdkVersion <= 16) {
                clazz.getMethod("collapse")
            } else {
                clazz.getMethod("collapsePanels")
            }
            collapse.isAccessible = true
            collapse.invoke(service)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }
}